﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace MisClient
{
    public partial class FrmPurchaseEnquiries : BaseForm
    {
        private IBLL.IDepart departBLL = MisCLL.DAOFactory.CreateInstance().GetRemoteDepart();
        private IBLL.IBacf bacfBLL = MisCLL.DAOFactory.CreateInstance().GetRemoteBacf();
        private IBLL.IGoods goodsBLL = MisCLL.DAOFactory.CreateInstance().GetRemoteGoods();
        private IBLL.IType typeTjBLL = MisCLL.DAOFactory.CreateInstance().GetRemoteType();
        private IBLL.ICustomer cusBLL = MisCLL.DAOFactory.CreateInstance().GetRemoteCustomer();
        private IBLL.ISupply supplyBLL = MisCLL.DAOFactory.CreateInstance().GetRemoteSupply();

        private WinPrint winPrint = new WinPrint();

        private int dataGridView = 0;
        private int printType = 1;

        public FrmPurchaseEnquiries()
        {
            InitializeComponent();
        }

        private void FrmPurchaseEnquiries_Load(object sender, EventArgs e)
        {
            this.openEndDate.Format = DateTimePickerFormat.Custom;
            this.openEndDate.CustomFormat = " ";
            this.openStarDate.Value = DateTime.Now.Date.AddDays(-7);
            this.txtDepCode.Text = accountUser.DeptCode;
            this.openStarDate.Focus();
        }

        private void openEndDate_ValueChanged(object sender, EventArgs e)
        {
            this.openEndDate.Format = DateTimePickerFormat.Long;
            this.openEndDate.CustomFormat = null;
        }

        private void txtID_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (!string.IsNullOrEmpty(this.txtID.Text.Trim()))
                {
                    MisEntity.Goods goods = goodsBLL.EndsWithID(this.txtID.Text.Trim());
                    if (goods == null)
                    {
                        MessageBox.Show("无此商品,请先设置！", "信息窗", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        this.txtID.Focus();
                        return;
                    }
                    this.txtGoods.Text = goods.GOODS;
                    this.txtDM.Text = goods.DM;
                    this.txtID.Text = goods.ID;
                }
                this.txtBei.Focus();
            }
        }

        private void txtDepCode_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (string.IsNullOrEmpty(this.txtDepCode.Text.Trim()))
                {
                    MessageBox.Show("部门代码不能为空！", "信息窗", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    this.txtDepCode.Focus();
                    return;
                }
                MisModel.Depart depart = departBLL.GetById(this.txtDepCode.Text.Trim());
                if (depart == null)
                {
                    MessageBox.Show("此部门无权操作！", "信息窗", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    this.txtDepCode.Focus();
                    return;
                }
                this.txtBoxDep.Text = depart.DepName;
                this.txtOper.Focus();
            }
        }

        private void txtGysCode_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (!string.IsNullOrEmpty(this.txtGysCode.Text.Trim()))
                {
                    MisModel.Supply supply = supplyBLL.GetById(this.txtGysCode.Text.Trim());
                    if (supply == null)
                    {
                        MessageBox.Show("供应商不存在,或无权操作！", "信息窗", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        this.txtGysCode.Focus();
                        return;
                    }
                    else
                        this.txtGysName.Text = supply.SuppName;
                }
                this.txtOper1.Focus();
            } 
        }

        private void txtType1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (!string.IsNullOrEmpty(this.txtType1.Text.Trim()))
                {
                    MisModel.Type type = typeTjBLL.GetType1ById(this.txtType1.Text.Trim());
                    if (type == null)
                    {
                        MessageBox.Show("统计类型不存在,或无权操作！", "信息窗", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        this.txtType1.Focus();
                        return;
                    }
                    else
                        this.textBox29.Text = type.TypeName;
                }
                this.txtType2.Focus();
            }
        }

        private void txtType2_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (!string.IsNullOrEmpty(this.txtType2.Text.Trim()))
                {
                    MisModel.Type type = typeTjBLL.GetType1ById(this.txtType2.Text.Trim());
                    if (type == null)
                    {
                        MessageBox.Show("统计类型不存在,或无权操作！", "信息窗", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        this.txtType2.Focus();
                        return;
                    }
                    else
                        this.textBox31.Text = type.TypeName;
                }
                this.txtType3.Focus();
            }
        }

        private void txtType3_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (!string.IsNullOrEmpty(this.txtType3.Text.Trim()))
                {
                    MisModel.Type type = typeTjBLL.GetType1ById(this.txtType3.Text.Trim());
                    if (type == null)
                    {
                        MessageBox.Show("统计类型不存在,或无权操作！", "信息窗", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        this.txtType3.Focus();
                        return;
                    }
                    else
                        this.textBox9.Text = type.TypeName;
                }
                this.btnOk.Focus();
            }
        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(this.txtDepCode.Text.Trim()))
            {
                MessageBox.Show("部门代码不能为空！", "信息窗", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                this.txtDepCode.Focus();
                return;
            }
            MisModel.Depart depart = departBLL.GetById(this.txtDepCode.Text.Trim());
            if (depart == null)
            {
                MessageBox.Show("此部门无权操作！", "信息窗", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                this.txtDepCode.Focus();
                return;
            }
            Dictionary<string, object> dictionary = new Dictionary<string, object>();
            StringBuilder sb = new StringBuilder();
            this.dataGridView1.Rows.Clear();
            if (!this.txtDepCode.Text.Trim().Equals("1"))
            {
                sb.Append(" and bf.dep_id=@depId");
                dictionary.Add("@depId", this.txtDepCode.Text.Trim());
            }
            sb.Append(" and bf.date>=@startDate");
            dictionary.Add("@startDate", this.openStarDate.Value.ToShortDateString());
            if (!string.IsNullOrEmpty(this.openEndDate.Text.ToString().Trim()))
            {
                sb.Append(" and bf.date<=@endDate");
                DateTime time = DateTime.Parse(this.openEndDate.Value.ToShortDateString());
                time = time.Date.AddDays(1);
                dictionary.Add("@endDate", time.ToShortDateString());
            }
            if (!string.IsNullOrEmpty(this.txtNo.Text.Trim()))
            {
                sb.Append(" and bf.no=@no");
                dictionary.Add("@no", this.txtNo.Text.Trim());
            }
            if (!string.IsNullOrEmpty(this.txtShopCode.Text.Trim()))
            {
                sb.Append(" and bf.shop_id=@shopId");
                dictionary.Add("@shopId", this.txtShopCode.Text.Trim());
            }
            if (!string.IsNullOrEmpty(this.txtType1.Text.Trim()))
            {
                sb.Append(" and g.type1=@type1");
                dictionary.Add("@type1", this.txtType1.Text.Trim());
            }
            if (!string.IsNullOrEmpty(this.txtType2.Text.Trim()))
            {
                sb.Append(" and g.type2=@type2");
                dictionary.Add("@type2", this.txtType2.Text.Trim());
            }
            if (!string.IsNullOrEmpty(this.txtType3.Text.Trim()))
            {
                sb.Append(" and g.type3=@type3");
                dictionary.Add("@type3", this.txtType3.Text.Trim());
            }
            if (!string.IsNullOrEmpty(this.txtGysCode.Text.Trim()))
            {
                sb.Append(" and bf.supp_id=@suppId");
                dictionary.Add("@suppId", this.txtGysCode.Text.Trim());
            }
            if (!string.IsNullOrEmpty(this.textBox4.Text.Trim()))
            {
                sb.Append(" and bf.JHTYPE=@JHTYPE");
                dictionary.Add("@JHTYPE", this.textBox4.Text.Trim());
            }
            if (!string.IsNullOrEmpty(this.txtID.Text.Trim()))
            {
                sb.Append(" and bf.id=@id");
                dictionary.Add("@id", this.txtID.Text.Trim());
            }
            if (!string.IsNullOrEmpty(this.txtBei.Text.Trim()))
            {
                sb.Append(" and bf.no_bei=@noBei");
                dictionary.Add("@noBei", this.txtBei.Text.Trim());
            }
            DataTable dt = bacfBLL.GetEnquiriesAll(sb.ToString(), dictionary);
            decimal count = 0;
            decimal price1 = 0;
            decimal price2 = 0;
            decimal price3 = 0;
            if (dt != null && dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    String[] DataRow = new String[18];
                    DataRow[0] = dt.Rows[i]["date"].ToString();
                    DataRow[1] = dt.Rows[i]["dep_id"].ToString();
                    DataRow[3] = string.Format("{0} {1}", dt.Rows[i]["supp_id"].ToString(), dt.Rows[i]["supply"].ToString());
                    DataRow[4] = string.Format("{0} {1}", dt.Rows[i]["id"].ToString(), dt.Rows[i]["goods"].ToString());
                    DataRow[5] = dt.Rows[i]["sl"].ToString();
                    count += decimal.Parse(DataRow[5]);
                    DataRow[6] = string.Format("{0}", (decimal.Parse(dt.Rows[i]["je"].ToString())/decimal.Parse(dt.Rows[i]["sl"].ToString())).ToString("f4"));
                    DataRow[7] = dt.Rows[i]["shop_id"].ToString();
                    DataRow[8] = dt.Rows[i]["je"].ToString();
                    price1 += decimal.Parse(DataRow[8]);
                    DataRow[9] = dt.Rows[i]["price1"].ToString();
                    price2 += decimal.Parse(DataRow[9]) * decimal.Parse(DataRow[5]);
                    DataRow[10] = dt.Rows[i]["ce"].ToString();
                    price3 += decimal.Parse(DataRow[10]);
                    DataRow[11] = dt.Rows[i]["cas"].ToString();
                    DataRow[12] = dt.Rows[i][14].ToString();
                    DataRow[13] = dt.Rows[i][16].ToString();
                    DataRow[14] = dt.Rows[i]["no"].ToString();
                    DataRow[15] = dt.Rows[i]["unit"].ToString();
                    DataRow[16] = dt.Rows[i]["jhtype"].ToString();
                    DataRow[17] = dt.Rows[i]["no_bei"].ToString();
                    this.dataGridView1.Rows.Add(DataRow);
                }
                this.label17.Text = string.Format("● 共{4}条 合计数量：{0} 进额：{1} 销额：{2} 未付金额：{3}", (int)count, price1, price2.ToString("f4"), price3, dt.Rows.Count);
            }
            else
            {
                this.label17.Text = "";
                MessageBox.Show("查无符合条件的记录！", "信息窗", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            
        }

        private void btnQuit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void openStarDate_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.openEndDate.Focus();
            }
        }

        private void openEndDate_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.txtNo.Focus();
            }
            
        }

        private void txtNo_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.txtDepCode.Focus();
            }
            
        }

        private void txtOper_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.textBox1.Focus();
            }
            
        }

        private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.txtGysCode.Focus();
            }
            
        }

        private void txtOper1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.txtShopCode.Focus();
            }
            
        }

        private void txtShopCode_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.textBox4.Focus();
            }
            
        }

        private void textBox4_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.txtOper2.Focus();
            }
            
        }

        private void txtOper2_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.txtID.Focus();
            }
            
        }

        private void txtBei_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.txtType1.Focus();
            }
            
        }

        private void btnRef_Click(object sender, EventArgs e)
        {
            Point mousePoint = MousePosition;
            Point point = this.PointToClient(mousePoint);
            this.contextMenuStrip1.Show(this, point);
        }

        private void toolStripMenuItem_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("calc.exe");
        }

        private void btnPri1_Click(object sender, EventArgs e)
        {
            this.dataGridView = 0;
            this.printType = 1;
            this.printPreviewDialog1.Document = this.printDocument1;
            this.printPreviewDialog1.PrintPreviewControl.Zoom = 1.0;
            this.printPreviewDialog1.ShowDialog();
        }

        private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            if (1 == this.printType)
                webPrint1(e);
            else if (2 == this.printType)
                webPrint2(e);
        }

        private void btnPri2_Click(object sender, EventArgs e)
        {
            this.dataGridView = 0;
            this.printType = 2;
            this.printPreviewDialog1.Document = this.printDocument1;
            this.printPreviewDialog1.PrintPreviewControl.Zoom = 1.0;
            this.printPreviewDialog1.ShowDialog();
        }

        private void webPrint1(System.Drawing.Printing.PrintPageEventArgs e)
        {
            string _Title = "新江厦汽车销售公司进货单打印";
            Font _TitleFont = new Font("宋体", 20, FontStyle.Bold);
            Point _CurrentPoint = new Point(30, 30);
            _CurrentPoint.X = (e.PageBounds.Width) / 2 - (int)(e.Graphics.MeasureString(_Title, _TitleFont).Width) / 2;
            e.Graphics.DrawString(_Title, _TitleFont, new SolidBrush(Color.Black), _CurrentPoint);
            StringBuilder sb = new StringBuilder();
            decimal sp = 0;
            decimal price = 0;
            sb.Append(string.Format("日期：{0}\n", DateTime.Now.ToShortDateString()));
            sb.Append("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n");
            sb.Append("录入日期  商品                                数量 单位      金额       销价   供应商\n");
            sb.Append("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n");
            if (this.dataGridView1.Rows.Count > 0)
            {
                DataGridViewRow dr = null;
                for (int i = dataGridView; i < this.dataGridView1.RowCount; i++, dataGridView++)
                {
                    dr = this.dataGridView1.Rows[i];
                    sb.Append(Convert.ToDateTime(dr.Cells[0].Value.ToString()).ToString("yy.MM.dd")).Append(" ");
                    sb.Append(winPrint.getGoodsStr(30, dr.Cells[4].Value.ToString()));
                    sb.Append(winPrint.getLenStr(11, decimal.Parse(dr.Cells[5].Value.ToString()).ToString("f2"))).Append(" ");
                    sp += decimal.Parse(dr.Cells[5].Value.ToString());
                    sb.Append(dr.Cells[15].Value.ToString()).Append(" ");
                    sb.Append(winPrint.getLenStr(12, decimal.Parse(dr.Cells[8].Value.ToString()).ToString("f2")));
                    price += decimal.Parse(dr.Cells[8].Value.ToString());
                    sb.Append(winPrint.getLenStr(10, decimal.Parse(dr.Cells[9].Value.ToString()).ToString("f2"))).Append(" ");
                    sb.Append(dr.Cells[3].Value.ToString().Split(' ')[0]).Append("\n");
                    if (i != 0 && i % 44 == 0)
                    {
                        dataGridView++;
                        break;
                    }
                }
            }
            sb.Append("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n");
            sb.Append(string.Format("合计数量：{0}  销额：{1}", sp.ToString("f2"), price.ToString("f2"))).Append("\n");
            sb.Append("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n");
            sb.Append(string.Format("制表：{0} 姓名{1}", accountUser.UserCode, accountUser.Oper));

            _CurrentPoint.X = 30;
            _CurrentPoint.Y += (int)(e.Graphics.MeasureString(_Title, _TitleFont).Height) + 20;
            Font _ContentFont = new Font("宋体", 12);
            e.Graphics.DrawString(sb.ToString(), _ContentFont, new SolidBrush(Color.Black), _CurrentPoint);
            if (dataGridView < this.dataGridView1.RowCount - 1)
                e.HasMorePages = true;
            else
                e.HasMorePages = false;
        }

        private void webPrint2(System.Drawing.Printing.PrintPageEventArgs e)
        {
            string _Title = "新江厦汽车销售公司进货单打印二";
            Font _TitleFont = new Font("宋体", 20, FontStyle.Bold);
            Point _CurrentPoint = new Point(30, 30);
            _CurrentPoint.X = (e.PageBounds.Width) / 2 - (int)(e.Graphics.MeasureString(_Title, _TitleFont).Width) / 2;
            e.Graphics.DrawString(_Title, _TitleFont, new SolidBrush(Color.Black), _CurrentPoint);
            StringBuilder sb = new StringBuilder();
            decimal sp = 0;
            decimal price1 = 0;
            decimal price2 = 0;
            sb.Append(string.Format("日期：{0}\n", DateTime.Now.ToShortDateString()));
            sb.Append("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n");
            sb.Append("录入日期  商品                                数量 单位    进价    进金额    销价 供应商\n");
            sb.Append("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n");
            if (this.dataGridView1.Rows.Count > 0)
            {
                DataGridViewRow dr = null;
                for (int i = dataGridView; i < this.dataGridView1.RowCount; i++, dataGridView++)
                {
                    dr = this.dataGridView1.Rows[i];
                    sb.Append(Convert.ToDateTime(dr.Cells[0].Value.ToString()).ToString("yy.MM.dd")).Append(" ");
                    sb.Append(winPrint.getGoodsStr(30, dr.Cells[4].Value.ToString()));
                    sb.Append(winPrint.getLenStr(10, decimal.Parse(dr.Cells[5].Value.ToString()).ToString("f2"))).Append(" ");
                    sp += decimal.Parse(dr.Cells[5].Value.ToString());
                    sb.Append(dr.Cells[15].Value.ToString());
                    sb.Append(winPrint.getLenStr(10, decimal.Parse(dr.Cells[6].Value.ToString()).ToString("f2")));
                    price1 += decimal.Parse(dr.Cells[6].Value.ToString());
                    sb.Append(winPrint.getLenStr(10, decimal.Parse(dr.Cells[8].Value.ToString()).ToString("f2")));
                    price2 += decimal.Parse(dr.Cells[8].Value.ToString());
                    sb.Append(winPrint.getLenStr(8, decimal.Parse(dr.Cells[9].Value.ToString()).ToString("f2"))).Append(" ");
                    sb.Append(dr.Cells[3].Value.ToString().Split(' ')[0]).Append("\n");
                    if (i != 0 && i % 44 == 0)
                    {
                        dataGridView++;
                        break;
                    }
                }
            }
            sb.Append("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n");
            sb.Append(string.Format("合计数量：{0}  进额：{1}  销额：{2}", sp.ToString("f2"),price1.ToString("f2"),price2.ToString("f2"))).Append("\n");
            sb.Append("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n");
            sb.Append(string.Format("制表：{0} 姓名{1}", accountUser.UserCode, accountUser.Oper));

            _CurrentPoint.X = 30;
            _CurrentPoint.Y += (int)(e.Graphics.MeasureString(_Title, _TitleFont).Height) + 20;
            Font _ContentFont = new Font("宋体", 12);
            e.Graphics.DrawString(sb.ToString(), _ContentFont, new SolidBrush(Color.Black), _CurrentPoint);
            if (dataGridView < this.dataGridView1.RowCount - 1)
                e.HasMorePages = true;
            else
                e.HasMorePages = false;
        }
    }
}
